Бинарная куча — это дерево, в котором значение родителя всегда больше или равно значениям его детей.
#include <vector>
#include <algorithm>
class MaxHeap {
std::vector<int> heap;
void siftUp(int i) {
while (i > 0 && heap[(i - 1) / 2] < heap[i]) {
std::swap(heap[i], heap[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
void siftDown(int i) {
int maxIdx = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < heap.size() && heap[l] > heap[maxIdx]) maxIdx = l;
if (r < heap.size() && heap[r] > heap[maxIdx]) maxIdx = r;
if (i != maxIdx) {
std::swap(heap[i], heap[maxIdx]);
siftDown(maxIdx);
}
}
public:
void insert(int val) {
heap.push_back(val);
siftUp(heap.size() - 1);
}
int extractMax() {
int res = heap[0];
heap[0] = heap.back();
heap.pop_back();
if (!heap.empty()) siftDown(0);
return res;
}
};